#!usr/bin/env python3
''' ssh 权限自动化开通系统'''

__author__ = 'caoyong'
#from app.app import APP
#from conf import config
#from conf.config import *
#from model.map_db import *
#from flask import send_file
import time
from flask import render_template
from flask import request
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
#from flask import session, make_response
from flask import redirect
import shutil
#app = APP(config)

#db = app.get_db()
#api = app.get_api()

#实例化
app = Flask(__name__)

#连接数据库
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = \
 "mysql+pymysql://cao:123123@192.168.0.59/ssh"
db = SQLAlchemy(app)

class user(db.Model):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    passwd = db.Column(db.String)
    department = db.Column(db.String)
    manager = db.Column(db.String)
    date = db.Column(db.Date)

class workOrder(db.Model):
    __tablename__ = "work_order"
    wo_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    servername = db.Column(db.String)
    u_publickey = db.Column(db.String)
    wo_time = db.Column(db.Date)
    wo_status = db.Column(db.String)
    wo_handle = db.Column(db.Date)

class server(db.Model):
    __tablename__ = "server"
    server_id = db.Column(db.Integer, primary_key=True)
    servername = db.Column(db.String)
    ip_addr = db.Column(db.String)
    server_address = db.Column(db.String)

#首页
@app.route('/')
def v_index():
    return render_template('/index.html')

#路由到登录页面
@app.route('/login')
def login():
    return render_template('/login.html')

#路由到注册页面
@app.route('/register')
def register():
    return render_template('/register.html')

@app.route('/user_auth', methods=['POST'])
def user_auth():
    '''登录验证功能'''
    userName = request.form['username']
    passwd = request.form['pwd']
    user_info = user.query.filter_by(username=userName).first()
    if user_info:
        if user_info.passwd == passwd:
            #session['user_id'] = user_info.user_id
            if userName == 'admin':
                return redirect('/handleorder')
            return render_template('/userorder.html')
        else:
            return "密码输入有误！请重新输入！"
    else:
        return "用户认证失败，请检查用户名和密码是否正确！"


@app.route('/register_user_db', methods=['POST'])
def add_user_info():
    try:
        user_info = user(username=request.form['username'], passwd=request.form['passwd'], department=request.form['dept'],
                     manager=request.form['lader'], date=time.strftime('%Y%m%d'))
        db.session.add(user_info)
        db.session.commit()
        return render_template('/success_register.html')
    except:
        return "用户名已存在，请重新输入！"

@app.route('/order', methods=['POST'])
def order():
    #try:
        order_info = workOrder(servername=request.form['servername'], u_publickey=request.form['pub_key'],
                               wo_time=time.strftime('%Y%m%d%H%M%S'),user_id=request.form['user_id'],wo_status='0')
        db.session.add(order_info)
        db.session.commit()
        return "提交订单成功"
    #except:
        #return "提交订单失败"

order_list = []
@app.route('/handleorder')
def handleorder():
    orderinfo = workOrder.query.filter_by(wo_status='0').all()
    global order_list
    order_list.clear()
    for i in orderinfo:
        order_content = {'wo_id': i.wo_id,
                        'user_id': i.user_id,
                        'servername': i.servername,
                        'user_publickey': i.u_publickey,
                        'wo_time': i.wo_time,
                        'wo_status': i.wo_status,
                        'wo_handle': i.wo_handle}
        order_list.append(order_content)

    handle_order = '''
        <p><h1><a href="/sendpublickey">处理订单</a></h1>
        <p><h1><a href="/static/serverinfo.html">服务器信息添加</a></h1>
        '''
    if orderinfo:
        return "订单信息:{0}".format(order_list)+handle_order
    else:
        return "没有要处理的订单"

@app.route('/sendpublickey')
def sendpublickey():
    server_name = order_list[0]['servername']
    publickey = order_list[0]['user_publickey']
    server_info = server.query.filter_by(servername=server_name).first()
    ip = server_info.ip_addr
    with open('/tmp/id_rsa.pub','w') as f1:
        f1.write(public_key)
    with open('/tmp/ip.txt','w') as f2:
        f2.write(ip)
    from sendkey import go
    from fabric.api import execute
    execute(go)
    return "密钥发送成功"

@app.route('/addserverinfo', methods=['POST'])
def addserverinfo():
    try:
        server_info = server(servername=request.form['servername'],ip_addr=request.form['ipaddr'],server_address=request.form['server_address'])
        db.session.add(server_info)
        db.session.commit()
        return "服务器信息添加成功"
    except:
        return "服务器信息已经存在，请重新输入"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8089, debug=True, threaded=True)
